package net.itbaiyang.pattern.component.adapter;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import net.itbaiyang.pattern.component.SmsComponent;
import net.itbaiyang.pattern.config.SmsConfig;
import net.itbaiyang.pattern.util.CommonUtil;
import net.itbaiyang.pattern.util.JsonData;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class SenderAdapter extends SmsComponent implements SmsSender{

    @Value("${smstext.path}")
    private String URL_TEMPLATE;

    @Resource
    private SmsConfig smsConfig;

    /**
     * 发送短信的方法
     * @param to 接收短信的手机号
     * @param value 短信中的验证码或其他参数
     * @return 返回发送结果
     */
    @Override
    public JsonData tencentSendCode(String to, String value) {
        // 记录方法开始时间
        long beginTime = CommonUtil.getCurrentTimestamp();

        // 构造短信参数，例如替换的验证码和有效时间
        String param = "**code**:"+value+",**minute**:10";
        // 格式化URL，将接收者号码、参数、签名ID和模板ID插入URL模板中
        String url = String.format(URL_TEMPLATE, to, param, smsConfig.getSmsSignId(), smsConfig.getTemplateId());

        // 创建一个可关闭的HttpClient实例
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 使用POST方法创建一个请求
            HttpPost httpPost = new HttpPost(url);
            // 设置请求头部的授权信息和内容类型
            httpPost.setHeader("Authorization", "APPCODE " + smsConfig.getAppCode());
            httpPost.setHeader("Content-Type", "application/json");

            // 如果需要发送请求体，将Map对象转换为JSON字符串后设置为请求的实体
            Map<String, String> bodys = new HashMap<>();
            StringEntity entity = new StringEntity(new ObjectMapper().writeValueAsString(bodys));
            httpPost.setEntity(entity);

            // 执行请求并获得响应
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                // 记录方法结束时间
                long endTime = CommonUtil.getCurrentTimestamp();
                // 将响应实体转换为字符串
                String responseBody = EntityUtils.toString(response.getEntity());
                // 记录请求的URL和响应体
                log.info("url={},body={}", endTime - beginTime, url, responseBody);

                // 检查响应状态码是否为2xx以判断请求是否成功
                if (response.getStatusLine().getStatusCode() >= 200 && response.getStatusLine().getStatusCode() < 300) {
                    // 请求成功，记录成功信息并返回包含响应信息的JsonData对象
                    log.info("发送短信成功,响应信息:{}", responseBody);
                    return JsonData.buildCodeAndMsg(1, responseBody);
                } else {
                    // 请求失败，记录错误信息并返回包含响应信息的JsonData对象
                    log.error("发送短信失败,响应信息:{}", responseBody);
                    return JsonData.buildCodeAndMsg(-1, responseBody);
                }
            }
        } catch (Exception e) {
            // 捕获异常，记录错误信息并返回包含异常信息的JsonData对象
            log.error("发送短信异常", e);
            return JsonData.buildCodeAndMsg(-1, e.getMessage());
        }
    }
}
